package com.xuan.yubi.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuan.yubi.annotation.AuthCheck;
import com.xuan.yubi.annotation.CountRecord;
import com.xuan.yubi.common.BaseResponse;
import com.xuan.yubi.common.DeleteRequest;
import com.xuan.yubi.common.ErrorCode;
import com.xuan.yubi.common.ResultUtils;
import com.xuan.yubi.constant.UserConstant;
import com.xuan.yubi.exception.BusinessException;
import com.xuan.yubi.exception.ThrowUtils;
import com.xuan.yubi.model.dto.chart.*;
import com.xuan.yubi.model.entity.Chart;
import com.xuan.yubi.model.entity.User;
import com.xuan.yubi.model.vo.BiResponse;
import com.xuan.yubi.service.ChartService;
import com.xuan.yubi.service.UserService;
import com.xuan.yubi.service.impl.ChartServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;

/**
 * 图表接口
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;


    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long chartId = deleteRequest.getId();
        boolean result = chartService.deleteChart(chartId, user.getId(), userService.isAdmin(user));

        return ResultUtils.success(result);
    }


    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        // 参数校验
        chartService.validChart(chart, false);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }


    @GetMapping("/get")
    public BaseResponse<Chart> getChartVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean isAdmin = userService.isAdmin(loginUser);

        Chart chart = chartService.getChartVoById(id, loginUser.getId(), isAdmin);
        return ResultUtils.success(chart);
    }


    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }


    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                         HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());

        Page<Chart> chartPage = chartService.listMyChartVOByPage(chartQueryRequest);
        return ResultUtils.success(chartPage);
    }


    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        // 参数校验
        chartService.validChart(chart, false);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }


    @CountRecord
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAiSync(@RequestPart("file") MultipartFile multipartFile,
                                                     GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        if (genChartByAiRequest == null || multipartFile.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        BiResponse biResponse = chartService.genChartByAiSync(multipartFile, genChartByAiRequest, loginUser.getId());
        return ResultUtils.success(biResponse);
    }


    @CountRecord
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                                      GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        if (genChartByAiRequest == null || multipartFile.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        BiResponse biResponse = chartService.genChartByAiAsync(multipartFile, genChartByAiRequest, loginUser.getId());
        return ResultUtils.success(biResponse);

    }


    @CountRecord
    @PostMapping("/gen/async/mq")
    public BaseResponse<BiResponse> genChartByAiAsyncMq(@RequestPart("file") MultipartFile multipartFile,
                                                        GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        if (genChartByAiRequest == null || multipartFile.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        BiResponse biResponse = chartService.genChartByAiAsyncMq(multipartFile, genChartByAiRequest, loginUser.getId());
        return ResultUtils.success(biResponse);
    }


    @PostMapping("/updateStatus")
    public BaseResponse<Boolean> updateChartStatusByParseError(@RequestBody ChartStatusRequest chartStatusRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(chartStatusRequest == null, ErrorCode.PARAMS_ERROR);
        // 判断是否登录和用户身份
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        boolean isAdmin = userService.isAdmin(loginUser);

        boolean result = chartService.updateStatusByParseError(chartStatusRequest.getId(), userId,isAdmin);
        return ResultUtils.success(result);
    }

    @PostMapping("/retryGen")
    public BaseResponse<Boolean> retryGen(@RequestBody RetryGenRequest retryGenRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(retryGenRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);

        boolean b = chartService.retryGen(retryGenRequest.getChartId(), loginUser.getId());
        return ResultUtils.success(b);
    }




}
